<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;
class Open extends Controller
{

    public function Index(){

        return $this->fetch('Index');
    }

    /**
     * 会员登录
     * @return mixed
     */
    public function Login_1()
    {
        //系统参数
        $Config = Config();
        if ($Config['web_switch'] == 0){
            $this->redirect('Open/WebOff');
        }
        $this->assign('title',$Config['web_name']);

        //Post请求操作
        if (IsPost()) {
            //请求数据
            $Data = Param();

            //查询条件
            $Where['username'] = $Data['username'];
            $Where['password_login'] = md5($Data['password_login']);

            //会员信息
            $UserInfo = UserInfo($Where);
            if (empty($UserInfo)) {
                return ['status' => 0, 'message' => '用户名或密码错误'];
            }else{
                if ($UserInfo['status'] == 0) {
                    return ['status' => 0, 'message' => '账号未激活'];
                } else {
                    Session::set('user_id', $UserInfo['id']);
                    return ['status' => 1, 'message' => '登录成功'];
                }
            }
        }else{
            //轮播图
            $BannerList = Db::name('banner')->where(['place'=>2])->order('xu asc')->select();
            $this->assign('BannerList',$BannerList);

            //查看是否有session值
            $UserID = Session::get('user_id');
            if(empty($UserID)){ //没有则说明没有登录，跳转到登录界面
                return $this->fetch('Login');
            }else {  //有则说明已登录，跳转到首页
                $this->redirect('Index/App');
            }


        }
    }
    
    //自动登录注册
    public function Login(){
        //获取微信用户信息
        // $info = $this->get_user_all();
        // $info = json_decode($info,true);
        // dump($info);
        Vendor('WxPayv3.JSAPI');
        $tools = new \JsApiPay();
        $openid = $tools->GetOpenid();
        // dump($openid);die;
        // dump($openid['access_token']);die;
        // $info = $this->get_user_info($openid['access_token'], $openid['openid']);
        // dump($info);die;
        // o7oxC6kfkoX94h1U3s_U2NqJ4q6E
        //判断该微信是否注册过
        $pd = Db::name('user')->where(['openid'=>$openid['openid'],'status'=>1])->find();
        if($pd !== null){
            // echo(1);die;
            //有的话直接登录
            Session::set('user_id', $pd['id']);
            $this->redirect('Index/index');
        }else{
            $pd1 = Db::name('user')->where(['openid'=>$openid['openid'],'status'=>0])->find();
            if($pd1){
                echo '<h1 style="text-align:center">当前账号已冻结!</h1>';die;
            }
            $info = $this->get_user_info($openid['access_token'], $openid['openid']);
            //没有就注册
            $Count = UserCount() + 1;
            $Data = Param();
             //推荐人信息看有没有
            if(array_key_exists('recommend',$Data)){
                $RecommendInfo = UserInfo(['username'=>$Data['recommend']]);
            }else{
                $RecommendInfo['id'] = 1;
            }
            // $wei = Db::name('wei')->where(['openid'=>$info['openid']])->find();
            //会员记录信息
            $AddData = [
                'username' => $info['nickname'],    //会员账号
                'openid' => $info['openid'],    //openid
                'head_url' => $info['headimgurl'],    //openid
                'password_login' => md5(123456), //登录密码md5加密
                'password_pay' => md5(123456), //支付密码md5加密
                'status' => 1, //激活状态 0未激活 1已激活 免费注册无需激活
                // 'phone' => $Data['phone'], //会员手机号
                'name' => $info['nickname'], //默认姓名
                'level' => 1, //默认等级 游客
                'add_time' => time(),   //注册时间
                'recommend' => $RecommendInfo['id'],    //推荐人ID
            ];
            
            if(Db::name('user')->insert($AddData)){
                //新添加的会员信息
                $UserInfo = UserInfo(['username'=>$AddData['username']]);

                // //创建推荐关系
                $user_id = $UserInfo['id'];
                $recommend_id = $AddData['recommend'];
                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend_id]);
                $yuan = Db::name('shun')->order('id desc')->find();
                $shun = explode(',',$yuan['str']);
//            //将移除的用户添加到末尾
                array_push($shun,$UserInfo['id']);//添加元素
//            //将顺序转化为字符串存起来
                $str = implode(',',$shun);
                Db::name('shun')->where(['id'=>$yuan['id']])->update(['str'=>$str]);
                //返回注册结果
                Session::set('user_id', $UserInfo['id']);
                $this->redirect('Index/index');
                exit();
            }else{
                echo '系统错误,请稍后重试';
                exit();
            }
        }
    }
    
    private $appId = 'wx5b5fbd4cdafaf65f';
    private $appSecret = '480a03ffeae1e9c7b881c2be9bfa3a9f';
    /**
     * 1、获取微信用户信息，判断有没有code，有使用code换取access_token，没有去获取code。
     * @return array 微信用户信息数组
     */
    public function get_user_all()
    {
        if (!isset($_GET['code'])) {//没有code，去微信接口获取code码
            $callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];//微信服务器回调url，这里是本页url;注意：：这里回调的url是http://www.klda.com/index.php。如果想要获取完整的路径用 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
            $this->get_code($callback);
        } else {//获取code后跳转回来到这里了
            $code = $_GET['code'];
            $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
            $data_all = $this->get_user_info($data['access_token'], $data['openid']);//获取微信用户信息
            //原来的返回
            // return json($data_all);
            //修改返回json
            return json_encode($data_all,true);
        }
    }
    /**
     * 2、用户授权并获取code
     * @param string $callback 微信服务器回调链接url
     */
    private function get_code($callback)
    {
        $appid = $this->appId;
        $scope = 'snsapi_userinfo';
        $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:$url");
    }

    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code)
    {
        $appid = $this->appId;
        $appsecret = $this->appSecret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . '<hr>msg  :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    private function get_user_info($access_token, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . '<hr>msg  :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        // var_dump($data);die;
        return $data;
    }


    /**
     * 会员注册
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Register(){
        //系统参数
        $Config = Config();
        if ($Config['web_switch'] == 0){
            $this->redirect('Open/WebOff');
        }
        $this->assign('title',$Config['web_name']);

        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();

            if(UserCount(["username" => $Data["username"]])){
                return ['status'=>0,'message'=>'该手机号已注册'];
            }

//            //判断验证码是否正确
//            $CodeRes = checkCode($Data['phone'],$Data['code']);
//            if($CodeRes['status'] != 1){
//                return $CodeRes;
//            }

            //推荐人信息
            $RecommendInfo = UserInfo(['username'=>$Data['recommend']]);
            if (!$RecommendInfo){
                return ['status'=>0,'message'=>'推荐人不存在'];
            }

            $Count = UserCount() + 1;
            //会员记录信息
            $AddData = [
                'username' => $Data['username'],    //会员账号
                'password_login' => md5($Data['password_login']), //登录密码md5加密
                'password_pay' => md5($Data['password_pay']), //支付密码md5加密
                'status' => 1, //激活状态 0未激活 1已激活 免费注册无需激活
                'phone' => $Data['phone'], //会员手机号
                'name' => '用户_'.$Count, //默认姓名
                'level' => 1, //默认等级 游客
                'add_time' => time(),   //注册时间
                'recommend' => $RecommendInfo['id'],    //推荐人ID
            ];

            //会员表中添加记录
            if(Db::name('user')->insert($AddData)){
                //新添加的会员信息
                $UserInfo = UserInfo(['username'=>$AddData['username']]);

                //创建推荐关系
                $user_id = $UserInfo['id'];
                $recommend_id = $AddData['recommend'];
                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend_id]);
                //返回注册结果
                Session::set('user_id', $UserInfo['id']);
                return ['status'=>1,'message'=>'注册成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }

        //推荐账号
        $Recommend = Param('recommend');
        $this->assign('Recommend',$Recommend);


        //轮播图
        $BannerList = Db::name('banner')->where(['place'=>2])->order('xu asc')->select();
        $this->assign('BannerList',$BannerList);

        return $this->fetch('Register');
    }


    /**
     * 找回密码
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function FindPass(){
        //系统参数
        $Config = Config();
        if ($Config['web_switch'] == 0){
            $this->redirect('Open/WebOff');
        }
        $this->assign('title',$Config['web_name']);

        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();

            //判断账号手机号是否匹配
            $UserInfo = UserInfo(['username'=>$Data['username'],'phone'=>$Data['phone']]);
            if(empty($UserInfo)){
                return ['status'=>0,'message'=>'账号与手机号不匹配'];
            }

//            //判断验证码是否正确
//            $CodeRes = checkCode($Data['phone'],$Data['code']);
//            if($CodeRes['status'] != 1){
//                return $CodeRes;
//            }

            //更新密码
            $Save['password_login'] = md5($Data['new_password']);
            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($Save)){
                return ['status'=>1,'message'=>'密码修改成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }

        //轮播图
        $BannerList = Db::name('banner')->where(['place'=>2])->order('xu asc')->select();
        $this->assign('BannerList',$BannerList);

        return $this->fetch('FindPass');
    }

    /**
     * 查询账号是否存在
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function CheckUser(){
        //请求数据
        $UserName = Param('username');

        //查询账号是否存在
        if(Db::name('user')->where(['username'=>$UserName])->find()){
            return ['status'=>true];
        }else{
            return ['status'=>false];
        }
    }

    /**
     * 发送短信验证码
     * @return array
     */
    public function SendCode(){
        //引用发送短信类
        require 'Smsapi.php';
        //接口账号
        $uid = 'yqdyqd111';
        //登录密码
        $pwd = 'yqdyqd111';

        /**
         * 实例化接口
         *
         * @param string $uid 接口账号
         * @param string $pwd 接口密码
         */
        $api = new SmsApi($uid,$pwd);

        //发送的手机 多个号码用,英文逗号隔开
        
       $mobile = Param('phone');
        //验证码
        $code = $api->randNumber();
        //短信内容
        $content = '【芭菲名媛】您的验证码是：'.$code.'，请及时完成验证。';

        //发送全文模板短信
        $result = $api->sendAll($mobile,$content);

        if($result['stat']=='100'){
            AddCode($mobile,$code);
            return ['status'=>1,'message'=>"发送成功"];
        }else{
            return ['status'=>0,'message'=>'发送失败:'.$result['stat'].'('.$result['message'].')'];
        }
    }

    public function SendCode_1(){
        //引用发送短信类
        require 'Smsapi.php';
        //接口账号
        $uid = 'yqdyqd111';
        //登录密码
        $pwd = 'yqdyqd111';

        /**
         * 实例化接口
         *
         * @param string $uid 接口账号
         * @param string $pwd 接口密码
         */
        $api = new SmsApi($uid,$pwd);

        //发送的手机 多个号码用,英文逗号隔开
        //用户信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $mobile = $UserInfo['phone'];
        //验证码
        $code = $api->randNumber();
        //短信内容
        $content = '【芭菲名媛】您的验证码是：'.$code.'，请及时完成验证。';

        //发送全文模板短信
        $result = $api->sendAll($mobile,$content);

        if($result['stat']=='100'){
            AddCode($mobile,$code);
            return ['status'=>1,'message'=>"发送成功"];
        }else{
            return ['status'=>0,'message'=>'发送失败:'.$result['stat'].'('.$result['message'].')'];
        }
    }

    /**
     * 退出登录
     */
    public function LoginOut(){
        Session::delete('user_id');

        //跳转登录界面
        $this->redirect('Open/Login_1');
    }

    /**
     * 系统关闭提示页面
     * @return mixed
     */
    public function WebOff(){
        //系统参数
        $Config = Config();
        $this->assign('Config',$Config);

        return $this->fetch('WebOff');
    }
    
    
    public function OrderWeChatGZNotify(){
        //获取返回的xml
        $testxml  = file_get_contents("php://input");

        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));

        //转成数组
        $result = json_decode($jsonxml, true);

        consume_log(var_export($result,true));

        if($result){

            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){

                //进行改变订单状态等操作。。。。
                $OrderInfo = Db::name('user_order')->where(['order_id'=>$result['out_trade_no']])->find();    //订单信息
                $pd = Db::name('finance')->where(['order_id'=>$OrderInfo['order_id']])->find();
                if($pd){
                    die;
                }
                //获取订单中的所有商品id  并分割
                $goodsid = explode(',', $OrderInfo['goods_id']);
                //看单商品还是多商品
                if(count($goodsid) == 1){
                    $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);    //用户信息
                    $goods = Db::name('goods')->where(['id'=>$OrderInfo['goods_id']])->find();
                    $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
                    $GoodInfo = Db::name('goods')->where(['id'=>$OrderInfo['goods_id'] ])->find();
                    $out_trade_no = $result['out_trade_no'];
                    //商品数量
                    $numb = $OrderInfo['num'];
                    if($OrderInfo['status'] == 0){  //订单状态为0 进行处理
                        //秒杀
                        if($OrderInfo['order_type'] == 4){
                            if($OrderInfo['num'] + $goods['sellnum'] > $goods['mnum'] ){
                                $OrderSave['status'] = 11;//待退款
                                $msg = '待退款';
                            }elseif($goods['etime'] < time()){
                                $OrderSave['status'] = 11;//待退款
                                $msg = '待退款';
                            }else{
                                $OrderSave['status'] = 1;
                                $msg = '秒杀商品购买';
                                
                                @$tj_money = $GoodInfo['reward_1']*$OrderInfo['num'];//推荐积分
                                @$tj_money1 = $GoodInfo['zhiyu']*$OrderInfo['num'];//推荐奖余额
                                //店铺级以上  直推奖励到余额    其他积分
                                // if($higherInfo['level'] >= 3){
                                //     $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                                //     $ms = '推荐奖余额';
                                //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                                // }else{
                                //     $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                                //     $ms = '推荐奖积分';
                                //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                                // }
                                $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                                    $ms = '推荐奖余额';
                                    if($tj_money1 > 0){
                                        FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                                    }

                                // $recommend['person_achievement']=$higherInfo['person_achievement']+$GoodInfo['reward_1'];  //个人收益
                                Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                                // FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 4, 11, $ms);
                                quyu($OrderInfo,$GoodInfo,$numb);
//                                dian($GoodInfo,$OrderInfo);
                                Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                                Db::name('goods')->where(['id'=>$OrderInfo['goods_id']])->setInc('sellnum',$OrderInfo['num']);
                            }
                            $OrderSave['pay_type'] = 9;
                            $OrderSave['pay_time'] = time();
                            $OrderSave['pay_amount'] = $OrderInfo['amount'];
                            Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                            FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg,$OrderInfo['order_id']);
                        //团购
                        }elseif($OrderInfo['order_type'] == 5){
                            $pt = Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->find();
                            //自己不能参与自己参加过的拼团
                            $can = explode(',',$pt['can']);
                            if(in_array($UserInfo['id'],$can)){
                                $OrderSave['status'] = 222;//待退款
                                $msg = '待退款';
                            }elseif($pt['status'] == 2){//拼团状态为2  说明结束了
                                $OrderSave['status'] = 333;//待退款
                                $msg = '待退款';
                            }elseif($pt['can_people'] >= $pt['pt_people']){//参与人数<= 总人数
                              $OrderSave['status'] = 666;//待退款
                              $msg = '待退款';
                            }else{
                                $OrderSave['status'] = 4;
                                $msg = '团购商品购买';
                                $OrderSave['pay_type'] = 9;
                                $OrderSave['pay_time'] = time();
                                $OrderSave['pay_amount'] = $OrderInfo['amount'];
                                Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                                FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg,$OrderInfo['order_id']);
                                if($OrderInfo['pt_id']){
                                    $pt_status['status'] = 1;//1为激活该拼团
                                    Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->update($pt_status);
                                }
                                
                                //2021.5.26 参与拼团修改is_pin字段
                                //用户信息
                                $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
                                $is_pin['is_pin'] = 1;
                                Db::name('user')->where(['id'=>$UserInfo['id']])->update($is_pin);
                                
                                
                                //参团     修改人数  拼接参团人  
                                tuan($OrderInfo);
                                kai($OrderInfo,$goods);
//                                dian($goods,$OrderInfo);
                            }
                        }else{
                            $OrderSave['status'] = 1;
                            $msg = '商品购买';
                            $OrderSave['pay_type'] = 9;
                            $OrderSave['pay_time'] = time();
                            $OrderSave['pay_amount'] = $OrderInfo['amount'];
                            Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                            FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg,$OrderInfo['order_id']);
                        }
                        
                        
                        // if($OrderInfo['order_type'] == 2){
                        //     //自己没2级就升级
                        //     if($UserInfo['level'] < 2){
                        //         $UserSave['level'] = 2;
                        //     }else{
                        //         $UserSave['level'] = $UserInfo['level'];
                        //     }
                        //     Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
                        // }
                        
//                        if($OrderInfo['order_type'] == 2){
//                            //自己没2级就升级
//                            if($UserInfo['level'] < 2){
//                                $UserSave['level'] = 2;
//                            }else{
//                                $UserSave['level'] = $UserInfo['level'];
//                            }
//                        }else{
//                            $UserSave['level'] = $UserInfo['level'];
//                        }

                        //2021.5.26新增拼过团买东西都成为会员
                        if($UserInfo['level'] == 1 && $UserInfo['is_pin'] == 1){
                            $UserSave['level'] = 2;
                        }else{
                            $UserSave['level'] = $UserInfo['level'];
                        }

                        if($OrderInfo['order_type'] == 2){
                            //判断is_sheng 0 不升级 1vip  2代理
                            if($goods['is_sheng'] == 1){
                                if($UserInfo['level'] < 2){
                                    $UserSave['level'] = 2;
                                }else{
                                    $UserSave['level'] = $UserInfo['level'];
                                }
                            }elseif($goods['is_sheng'] == 2){
                                if($UserInfo['level'] < 3){
                                    $UserSave['level'] = 3;
                                }else{
                                    $UserSave['level'] = $UserInfo['level'];
                                }
                            }else{
                                $UserSave['level'] = $UserInfo['level'];
                            }
                        }
                        

                        
                        Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
                        
                        //将总金额存入 setInc
                        Db::name('system_config')->where(['id'=>1])->setInc('month_all',$OrderInfo['amount']);
                        Db::name('system_config')->where(['id'=>1])->setInc('money_all',$OrderInfo['amount']);
                        
                          $fg_money=0;
                        $tj_money=0;
                        
                        
                        
                        //复购
//                        if($OrderInfo['order_type'] == 3){
//                            // //区域奖
//                            quyu($OrderInfo,$GoodInfo,$numb);
//                        }
                        
                        //礼包商品
                        if($OrderInfo['order_type'] == 2 || $OrderInfo['order_type'] == 3){//报单
                            @$tj_money = $GoodInfo['reward_1']*$OrderInfo['num'];//推荐奖
                            @$tj_money1 = $GoodInfo['zhiyu']*$OrderInfo['num'];//推荐奖
                            //店铺级以上  直推奖励到余额    其他积分
                            // if($higherInfo['level'] >= 3){
                            //     $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            //     $ms = '推荐奖余额';
                            //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                            // }else{
                            //     $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                            //     $ms = '推荐奖积分';
                            //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                            // }
                            //2021.5.26  改成全部送余额
                            $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            $ms = '推荐奖余额';
                            if($tj_money1 > 0){
                                FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                            }

                            Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                            //店铺奖励
//                            dian($GoodInfo,$OrderInfo);
                             Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                            // //区域奖
                            quyu($OrderInfo,$GoodInfo,$numb);

                            // //升级
                            uplevel($OrderInfo);
                            //级差奖
                            jicha($goods,$OrderInfo,$numb,$UserInfo['level']);
                            
                        }
                    }
                }elseif(count($goodsid) > 1){
                    $OrderSave['status'] = 1;
                    $msg = '商品购买';
                    $OrderSave['pay_type'] = 9;
                    $OrderSave['pay_time'] = time();
                    $OrderSave['pay_amount'] = $OrderInfo['amount'];
                    Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                    FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg,$OrderInfo['order_id']);
                    //将总金额存入 setInc
                    Db::name('system_config')->where(['id'=>1])->setInc('month_all',$OrderInfo['amount']);
                    Db::name('system_config')->where(['id'=>1])->setInc('money_all',$OrderInfo['amount']);
                    $fg_money=0;
                    $tj_money=0;
                    foreach ($goodsid as $key => $value) {
                        $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);    //用户信息
                        $goods = Db::name('goods')->where(['id'=>$value])->find();
                        $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
                        $GoodInfo = Db::name('goods')->where(['id'=>$value])->find();
                        $out_trade_no = $result['out_trade_no'];
                        $nums = explode(',',$OrderInfo['num']);
                        $numb = $nums[$key];
                        //复购
//                        if($GoodInfo['goods_type'] == 3){
//                            // //区域奖
//                            quyu($OrderInfo,$GoodInfo,$numb);
//                        }
                        //礼包商品
                        if($GoodInfo['goods_type'] == 2 || $GoodInfo['order_type'] == 3){//报单
                            @$tj_money = $GoodInfo['reward_1']*$numb;//推荐奖
                            @$tj_money1 = $GoodInfo['zhiyu']*$numb;//推荐奖
                            //店铺级以上  直推奖励到余额    其他积分
                            // if($higherInfo['level'] >= 3){
                            //     $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            //     $ms = '推荐奖余额';
                            //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                            // }else{
                            //     $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                            //     $ms = '推荐奖积分';
                            //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                            // }
                            $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                                $ms = '推荐奖余额';
                                if($tj_money1 > 0){
                                    FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                                }

                            Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                            //店铺奖励
//                            dian($GoodInfo,$OrderInfo);
                             Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                            // //区域奖
                            quyu($OrderInfo,$GoodInfo,$numb);

                            // //升级
                            uplevel($OrderInfo);
                            //级差奖
                            jicha($goods,$OrderInfo,$numb,$UserInfo['level']);
                            
                        }
                    }

                }


                
            }
            
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
        }
    }
    
    //测试退款
    public function ce(){
        wxrefund('20210623195647237','1','1');
        // $GoodInfo = Db::name('goods')->where(['id'=>'16' ])->find();
        // $OrderInfo = Db::name('user_order')->where(['order_id'=>'20210414181034064'])->find();    //订单信息
        // quyu($OrderInfo,$GoodInfo);
    }
    
    //测试逻辑
    public function ceshi1(){
        //panduan
        //进行改变订单状态等操作。。。。
        $out_trade_no = '20210415114128547';
                $OrderInfo = Db::name('user_order')->where(['order_id'=>$out_trade_no])->find();    //订单信息
                $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);    //用户信息
                $goods = Db::name('goods')->where(['id'=>$OrderInfo['goods_id']])->find();
                $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
                    $GoodInfo = Db::name('goods')->where(['id'=>$OrderInfo['goods_id'] ])->find();
                // $GoodInfo = Db::name('goods')->where(['id'=>$OrderInfo['goods_id'] ])->find();
                
                    //秒杀
                    if($OrderInfo['order_type'] == 4){
                        echo(1);
                        if($OrderInfo['num'] + $goods['sellnum'] > $goods['mnum'] ){
                            echo(2);die;
                            $OrderSave['status'] = 11;//待退款
                            $msg = '待退款';
                        }elseif($goods['etime'] < time()){
                            echo(3);die;
                            $OrderSave['status'] = 11;//待退款
                            $msg = '待退款';
                        }else{
                            echo(4);
                            $OrderSave['status'] = 1;
                            $msg = '秒杀商品购买';
                            
                            $tj_money = $goods['reward_1']*$OrderInfo['num'];//推荐积分
                            $tj_money1 = $goods['zhiyu']*$OrderInfo['num'];//推荐奖余额
                            //店铺级以上  直推奖励到余额    其他积分
                            if($higherInfo['level'] >= 3){
                                $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                                $ms = '推荐奖余额';
                                FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                            }else{
                                $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                                $ms = '推荐奖积分';
                                FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                            }
                            // $recommend['person_achievement']=$higherInfo['person_achievement']+$GoodInfo['reward_1'];  //个人收益
                            Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                            // FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 4, 11, $ms);
                            quyu($OrderInfo,$goods);
                            dian($goods,$OrderInfo);
                            Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                            Db::name('goods')->where(['id'=>$OrderInfo['goods_id']])->setInc('sellnum',$OrderInfo['num']);
                        }
                        $OrderSave['pay_type'] = 9;
                        $OrderSave['pay_time'] = time();
                        $OrderSave['pay_amount'] = $OrderInfo['amount'];
                        Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                        FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg);
                    //团购
                    }elseif($OrderInfo['order_type'] == 5){
                        $pt = Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->find();
                        //自己不能参与自己参加过的拼团
                        $can = explode(',',$pt['can']);
                        if(in_array($UserInfo['id'],$can)){
                            $OrderSave['status'] = 222;//待退款
                            $msg = '待退款';
                        }elseif($pt['status'] == 2){//拼团状态为2  说明结束了
                            $OrderSave['status'] = 333;//待退款
                            $msg = '待退款';
                        }elseif($pt['can_people'] >= $pt['pt_people']){//参与人数<= 总人数
                          $OrderSave['status'] = 666;//待退款
                          $msg = '待退款';
                        }else{
                            $OrderSave['status'] = 4;
                            $msg = '团购商品购买';
                            $OrderSave['pay_type'] = 9;
                            $OrderSave['pay_time'] = time();
                            $OrderSave['pay_amount'] = $OrderInfo['amount'];
                            Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                            FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg);
                            if($OrderInfo['pt_id']){
                                $pt_status['status'] = 1;//1为激活该拼团
                                Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->update($pt_status);
                            }
                            //参团     修改人数  拼接参团人  
                            tuan($OrderInfo);
                            kai($OrderInfo,$goods);
                            dian($goods,$OrderInfo);
                        }
                    }else{
                        $OrderSave['status'] = 1;
                        $msg = '商品购买';
                        $OrderSave['pay_type'] = 9;
                        $OrderSave['pay_time'] = time();
                        $OrderSave['pay_amount'] = $OrderInfo['amount'];
                        Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave);
                        FinanceAdd($OrderInfo['user_id'],$OrderInfo['user_id'],$OrderInfo['amount'],9,201,$msg);
                    }
                    
                    
                    if($OrderInfo['order_type'] == 2){
                        //自己没2级就升级
                        if($UserInfo['level'] < 2){
                            $UserSave['level'] = 2;
                        }else{
                            $UserSave['level'] = $UserInfo['level'];
                        }
                        Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
                    }
                    
                
                    
                    
                    //将总金额存入 setInc
                    Db::name('system_config')->where(['id'=>1])->setInc('month_all',$OrderInfo['amount']);
                    Db::name('system_config')->where(['id'=>1])->setInc('money_all',$OrderInfo['amount']);
                    
                      $fg_money=0;
                    $tj_money=0;
                    
                    
                    
                    //秒杀
                    if($OrderInfo['order_type'] == 4){
                        
                    }
                    
                    //礼包商品
                    if($OrderInfo['order_type'] == 2){//报单
                        $tj_money = $GoodInfo['reward_1']*$OrderInfo['num'];//推荐奖
                        $tj_money1 = $GoodInfo['zhiyu']*$OrderInfo['num'];//推荐奖
                        //店铺级以上  直推奖励到余额    其他积分
                        if($higherInfo['level'] >= 3){
                            $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            $ms = '推荐奖余额';
                            FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                        }else{
                            $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                            $ms = '推荐奖积分';
                            FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                        }
                        Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                        //店铺奖励
                        dian($GoodInfo,$OrderInfo);
                         Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                        // //区域奖
                        quyu($OrderInfo,$GoodInfo);
                        
                    }
    }
    
    public function wxrefund($out_trade_no,$total_fee,$refund_fee){
        require_once __DIR__."/../../../vendor/WxPayv3/lib/WxPay.Api.php";
        require_once __DIR__."/../../../vendor/WxPayv3/lib/WxPay.Config.php";
        require_once __DIR__."/../../../vendor/WxPayv3/lib/WxPay.Data.php";
        $out_trade_no = $out_trade_no;
        $total_fee = $total_fee;
        $refund_fee =$refund_fee;
        $input = new \WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $input->SetOut_refund_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        dump(\WxPayApi::refund($input));
        exit();
    }
    
    //每月分红
    public function month(){
        //系统参数
        $Config = Config();
        //一星董事
        $one = Db::name('user')->where(['level'=>10])->select();
        //人数
        $onecount = count($one);
        if($onecount != 0 && $Config['month_all'] != 0){
            //每人分得多少
            $money = $Config['month_all']*$Config['yi']/$onecount;
            foreach ($one as $v){
                $tj_money = $money*$Config['yu'];//余额
                $tj_money1 = $money*$Config['ji'];//积分
                $new['balance_4']=$v['balance_4']+$tj_money;  //余额
                $new['balance_1']=$v['balance_1']+$tj_money1;  //积分
                $new['person_achievement']=$v['person_achievement']+$money;  //个人收益
                FinanceAdd($v['id'], $v['id'], $tj_money, 4, 11, '分红余额');
                FinanceAdd($v['id'], $v['id'], $tj_money1, 1, 11, '分红积分');
                Db::name('user')->where(['id'=>$v['id']])->update($new);
            }
        }
        //二星董事
        $two = Db::name('user')->where(['level'=>11])->select();
        //人数
        $twocount = count($two);
        if($twocount != 0 && $Config['month_all'] != 0){
            //每人分得多少
            $money = $Config['month_all']*$Config['er']/$twocount;
            foreach ($two as $val){
                $tj_money = $money*$Config['yu'];//推荐奖余额
                $tj_money1 = $money*$Config['ji'];//推荐奖积分
                $new['balance_4']=$val['balance_4']+$tj_money;  //推荐奖励余额
                $new['balance_1']=$val['balance_1']+$tj_money1;  //推荐奖励积分
                $new['person_achievement']=$val['person_achievement']+$money;  //个人收益
                FinanceAdd($val['id'], $val['id'], $tj_money, 4, 11, '分红余额');
                FinanceAdd($val['id'], $val['id'], $tj_money1, 1, 11, '分红积分');
                Db::name('user')->where(['id'=>$val['id']])->update($new);
            }
        }
        //三星董事
        $three = Db::name('user')->where(['level'=>12])->select();
        //人数
        $threecount = count($three);
        if($threecount != 0 && $Config['month_all'] != 0){
            //每人分得多少
            $money = $Config['month_all']*$Config['san']/$threecount;
            foreach ($three as $value){
                $tj_money = $money*$Config['yu'];//推荐奖余额
                $tj_money1 = $money*$Config['ji'];//推荐奖积分
                $new['balance_4']=$value['balance_4']+$tj_money;  //推荐奖励余额
                $new['balance_1']=$value['balance_1']+$tj_money1;  //推荐奖励积分
                $new['person_achievement']=$value['person_achievement']+$money;  //个人收益
                FinanceAdd($value['id'], $value['id'], $tj_money, 4, 11, '分红余额');
                FinanceAdd($value['id'], $value['id'], $tj_money1, 1, 11, '分红积分');
                Db::name('user')->where(['id'=>$value['id']])->update($new);
            }
        }
        Db::name('system_config')->where(['id'=>1])->update(['month_all'=>0]);
    }
    
    //退款
    public function tui(){
        //获取所有退款订单
        $orders = Db::name('user_order')->where(['status'=>11])->select();
        if($orders){
            //处理
            foreach($orders as $v){
                $pt = Db::name('user_pt')->where(['pt_id'=>$v['pt_id']])->find();
                $info = Db::name('user')->where(['id'=>$v['user_id']])->find();
                //判断退余额还是微信
                //余额
                if($v['pay_type'] == 3){
                    $back['balance_4'] = $info['balance_4'] + $v['pay_amount'] + $pt['hongbao'];
                    //秒杀
                    if($v['order_type'] == 4){
                        $msg = '秒杀退款';
                    //拼团
                    }elseif($v['order_type'] == 5){
                        $msg = '拼团退款';
                    }else{
                        $msg = '退款';
                    }
                    FinanceAdd($info['id'], $info['id'], $v['pay_amount'], 4, 11, $msg);
                    FinanceAdd($info['id'], $info['id'], $pt['hongbao'], 4, 11, '拼团失败红包');
                    Db::name('user')->where(['id'=>$info['id']])->update($back);
                    $newstatus['status'] = 12;
                    Db::name('user_order')->where(['id'=>$v['id']])->update($newstatus);
                }elseif($v['pay_type'] == 9){
                    $out_trade_no = $v['order_id'];
                    $total_fee = $v['pay_amount']*100;
                    $refund_fee = $v['pay_amount']*100;
                    wxrefund($out_trade_no,$total_fee,$refund_fee);
                    $newstatus['status'] = 12;
                    Db::name('user_order')->where(['id'=>$v['id']])->update($newstatus);
                    FinanceAdd($info['id'], $info['id'], $refund_fee, 9, 11, $msg);
                    $back['balance_4'] = $info['balance_4'] + $pt['hongbao'];
                    Db::name('user')->where(['id'=>$info['id']])->update($back);
                    FinanceAdd($info['id'], $info['id'], $pt['hongbao'], 4, 11, '拼团失败红包');
                }
            }
        }
        
    }
    
    //拼团失败
    public function backpt(){
        $orders = Db::name('user_pt')->where(['status'=>1])->select();
        if($orders){
            //判断时间有没有超过24小时
            foreach ($orders as $v){
                //24小时
                $latertime = $v['add_time'] + 60*60*24;
                //24小时  小于现在时间
                if($latertime < time()){
                    //拼团退出  拼团状态改为5  订单改为11待退款
                    $pint['status'] = 5;
                    Db::name('user_pt')->where(['id'=>$v['id']])->update($pint);
                    $user_order = Db::name('user_order')->where(['pt_id'=>$v['pt_id']])->select();
                    if($user_order){
                        foreach ($user_order as $val){
                            $orderstatus['status'] = 11;
                            Db::name('user_order')->where(['id'=>$val['id']])->update($orderstatus);
                            
                        }
                    }
                }
            }
        }
    }
    
}
